<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view scroll">
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px" v-loading="loading">
            <el-row :gutter="24">
                <el-col :span="7" class="mb20">
                    <el-form-item label="考试名称" prop="examName">
                        <el-input v-model="form.examName" placeholder="请输入考试名称"/>
                    </el-form-item>
                </el-col>
                <el-col :span="7" class="mb20">
                    <el-form-item label="考试标签" prop="examLabel">
                        <el-input v-model="form.examLabel" placeholder="请输入考试标签"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8"></el-col>
                <el-col :span="2" class="mb20">
                    <el-button type="primary" @click="onSubmit" :disabled="started1">保存</el-button>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="7" class="mb20">
                    <el-form-item label="管理员姓名"  prop="adminName">
                        <el-input v-model="form.adminName" placeholder="管理员姓名"/>
                    </el-form-item>
                    <el-form-item label="管理员工号" prop="adminUserName">
                        <el-input v-model="form.adminUserName" placeholder="管理员工号"/>
                    </el-form-item>
                </el-col>
                <el-col :span="7" class="mb20">
                    <el-form-item  label="参考组织" prop="groupIds">
                        <el-cascader v-model="form.groupIds" ref="cascaderAddr1" style="width: 420px" @visible-change="handleVisibleChange" filterable
                                     placeholder="请选择" @change="handleCascaderChange1" :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true }"
                                     :options="options1" clearable  :disabled="started">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="参考岗位" prop="postNames">
                        <el-select  @change="getItem1" v-model="form.postNames" multiple filterable clearable collapse-tags collapse-tags-tooltip  placeholder="请选择" style="width: 240px" :disabled="started">
                            <el-option v-for="item in postList" :key="item.postsString" :label="item.postName" :value="item.postName" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="参考人员" prop="persons">
                        <el-select  @change="getItem2" v-model="persons"  multiple  filterable clearable collapse-tags collapse-tags-tooltip  placeholder="请选择" style="width: 240px">
                            <el-checkbox v-model="checked" @change='selectAll' style="margin-left: 20px">全选</el-checkbox>
                            <el-option v-for="item in personList" :key="item.username" :label="item.name+'-'+item.postName" :value="item.username"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="7" class="mb20">
                    <el-form-item label="创建试卷" prop="examPaperName">
                        <el-input v-model="form.examPaperName" disabled/>
                    </el-form-item>
                    <el-form-item>
<!--                        <el-button type="primary" v-if="flag == 0" text :disabled="form.postNames.length==0"-->
<!--                                   @click="formDialogRef.openDialog(form.groupIds,form.groupNames,processedPKPosts,form.examPaperId,0,form.examId)">新建试卷</el-button>-->
<!--                        <el-button type="primary" v-if="isShow"  text :disabled="form.postNames.length==0"-->
<!--                                   @click="formDialogRef.openDialog(form.groupIds,form.groupNames,processedPKPosts,form.examPaperId,1,form.examId)">编辑试卷</el-button>-->
                        <el-button type="primary" v-if="flag == 0" text :disabled="form.postNames.length==0"
                                   @click="formSelectDialogRef.openSelectDialog(processedPKPosts,form.examPaperId,0,form.examId)">新建试卷</el-button>
                        <el-button type="primary" v-if="isShow"  text :disabled="form.postNames.length==0"
                                   @click="formSelectDialogRef.openSelectDialog( processedPKPosts,form.examPaperId,1,form.examId)">编辑试卷</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="16" class="mb20">
                    <el-form-item label="考试说明" prop="examRemark">
                        <el-input  type="textarea" v-model="form.examRemark" placeholder="请输入"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="3" class="mb20">
                    <el-form-item label="提前交卷" prop="submitInadvanceState">
                        <el-switch  v-model="form.submitInadvanceState"  :active-value="0" :inactive-value="1"/>
                    </el-form-item>
                </el-col>
                <el-col :span="3"  v-if="form.submitInadvanceState==0">
                    <el-form-item label="允许交卷时间：" style="margin-left: 35px"></el-form-item>
                </el-col>
                <el-col :span="6"  v-if="form.submitInadvanceState==0">
                    <el-form-item label="考试开始后" prop="allowStartTime">
                        <el-input-number v-model="form.allowStartTime" :min="0" :max="60"/>
                    </el-form-item>
                </el-col>
                <el-col :span="2" style="margin-left: -12px" v-if="form.submitInadvanceState==0">
                    <el-text class="input3">分钟</el-text>
                </el-col>
                <el-col :span="3" class="mb20">
                    <el-form-item label="错题优先" prop="wrongQuestionFirstState">
                        <el-switch v-model="form.wrongQuestionFirstState"   :active-value="0" :inactive-value="1"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="5" class="mb20" style="margin-left: 10px">
                    <el-form-item label="考试类型：" prop="examType">
                        <el-radio-group v-model="form.examType" @change="change1">
                            <el-radio :label='0'>正式考试</el-radio>
                            <el-radio :label='1'>模拟考试</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="3" class="mb20" >
                    <el-form-item style="color: #817B7B" label="是否发放证书" prop="grantCertificateState">
                        <el-switch v-model="form.grantCertificateState" @change="change2" :disabled="form.examType==1"  :active-value="0" :inactive-value="1"/>
                    </el-form-item>
                </el-col>
                <el-col :span="5" class="mb20" v-if="form.grantCertificateState==0" >
                    <el-form-item label-width="250px" style="color: #817B7B" label="已取的证书人员也需要参加考试" prop="certificateHolderState">
                        <el-switch v-model="form.certificateHolderState" @change="change3" :disabled="form.examType==1"  :active-value="0" :inactive-value="1"/>
                    </el-form-item>
                </el-col>
                <el-col :span="5" v-if="form.grantCertificateState==0" >
                    <el-form-item label="考试在" prop="passingScore">
                        <el-input-number v-model="form.passingScore" @change="changeScore"  :min="0" :max="100" class="input5"/>
                        <el-text class="content2">分及以上</el-text>
                    </el-form-item>
                </el-col>
                <el-col :span="5" v-if="form.grantCertificateState==0">
                    <el-form-item label="选择证书" prop="certificateId">
                        <el-select   v-model="form.certificateId"  filterable collapse-tags collapse-tags-tooltip
                                     @change="getItem3"   placeholder="请选择" style="width: 240px" :disabled="form.examType==1">
                            <el-option v-for="item in certificateList" :key="item.certificateTemplateId" :label="item.certificateTemplateName" :value="item.certificateTemplateId" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="3" class="mb20">
                    <el-form-item label="电子监考" prop="electronicInvigilationState">
                        <el-switch v-model="form.electronicInvigilationState"  :active-value="0" :inactive-value="1"/>
                    </el-form-item>
                </el-col>
                <el-col :span="7" class="mb20" v-if="form.electronicInvigilationState==0">
                    <el-form-item label-width="210px" label="考试前人脸验证次数" prop="faceRecognitionTimes" >
                        <el-input-number v-model="form.faceRecognitionTimes" :min="5" :max="100"/>
                    </el-form-item>
                </el-col>
                <el-col :span="5" class="mb20"  v-if="form.electronicInvigilationState==0">
                    <el-form-item label="允许切屏次数" prop="cutscreenTimes">
                        <el-input-number v-model="form.cutscreenTimes" :min="0" :max="60"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="3" class="mb20">
                    <el-form-item label="允许补考" prop="allowMakeupExamState">
                        <el-switch v-model="form.allowMakeupExamState" :active-value="0" :inactive-value="1"/>
                    </el-form-item>
                </el-col>
                <el-col :span="5" class="mb20" v-if="form.allowMakeupExamState==0">
                    <el-form-item label="允许补考次数" prop="makeupTimes">
                        <el-input-number v-model="form.makeupTimes" :min="0" :max="60"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6" class="mb20">
                    <el-form-item label-width="150px" label="考试结束前" prop="sendRemindTime">
                        <el-input-number v-model="form.sendRemindTime" :min="0" :max="60"/>
                    </el-form-item>
                </el-col>
                <el-col :span="4" style="margin-left: -12px">
                    <el-text class="input3">分钟发送提醒(加默认值)</el-text>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="5" class="mb20">
                    <el-form-item label="考试时长" prop="examTime" style="font-weight: bold">
                        <el-input-number v-model="form.examTime" :min="30" :max="180" @change="changeTime"/>
                    </el-form-item>
                </el-col>
                <el-col :span="4" style="margin-left: -12px">
                    <el-text style="margin-left: 20px;line-height: 32px">分钟</el-text>
                </el-col>
            </el-row>
            <div class="line"></div>
            <el-row :gutter="24">
                <el-col :span="9" class="mb20" style="margin-left: 50px">
                    <el-text class="content">考试状态</el-text>
                    <el-form-item style="margin-left: 30px" label="选择时间" prop="examTimeState">
                        <el-radio-group v-model="form.examTimeState">
                            <el-radio :label="0">任意时间</el-radio>
                            <el-radio :label="1">指定时间</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <templet v-if="form.examTimeState==1">
                        <el-form-item label="开始时间" prop="specifyTimeStart">
                            <el-date-picker type="datetime" placeholder="请选择" v-model="form.specifyTimeStart"  format="YYYY-MM-DD HH:mm:ss" @change="changeTime"
                                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="结束时间" prop="specifyTimeEnd">
                            <el-date-picker type="datetime" placeholder="请选择" v-model="form.specifyTimeEnd"  format="YYYY-MM-DD HH:mm:ss" :disabled="form.examType==0"
                                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                        </el-form-item>
                    </templet>
                </el-col>
                <el-col :span="9" class="mb20" style="margin-left: 120px">
                    <el-text class="content">试题显示</el-text>
                    <el-form-item style="margin-left: 50px" label="试题顺序：" prop="questionOrder">
                        <el-radio-group v-model="form.questionOrder">
                            <el-radio :label="0">顺序</el-radio>
                            <el-radio :label="1">随机</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item style="margin-left: 50px" label="选项顺序：" prop="optionsOrder">
                        <el-radio-group v-model="form.optionsOrder">
                            <el-radio :label="0">顺序</el-radio>
                            <el-radio :label="1">随机</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="line"></div>
            <el-row :gutter="24">
                <el-col :span="11" class="mb20" style="margin-left: 100px">
                    <el-text style="line-height: 50px;margin-left: 10px;font-size: 16px">完成试卷</el-text>
                    <el-form-item style="margin-left: 70px;font-weight: bold" label="及格分数:">
                        <div style="display: flex">
                            <el-text >{{form.passingScore}}分</el-text>
                        </div>
                    </el-form-item>
                    <el-form-item  label="">
                        <el-input-number v-model="leftBoundary0" :min="0" :max="100" class="input5" disabled/>
                        <el-text style="font-weight: bold;margin-left: 5px;margin-right: 5px"><=得分<</el-text>
                        <el-input-number v-model="rightBoundary0" :min="1" :max="100" class="input5" disabled/>
                        <el-text class="content1">评价:</el-text>
                        <el-input v-model="scoreLevel0" placeholder="" class="input4"/>
                        <el-text>(不及格分数段)</el-text>
                    </el-form-item>
                    <el-form-item  label="">
                        <el-input-number v-model="leftBoundary1"  :min="0" :max="100" class="input5" @change="changeMark"/>
                        <el-text style="font-weight: bold;margin-left: 5px;margin-right: 5px"><=得分<</el-text>
                        <el-input-number v-model="rightBoundary1" :min="1" :max="100" class="input5" disabled/>
                        <el-text class="content1">评价:</el-text>
                        <el-input v-model="scoreLevel1" placeholder="" class="input4"/>
                    </el-form-item>
                    <el-form-item   label="">
                        <el-input-number v-model="leftBoundary2"  :min="0" :max="100" class="input5" @change="changeMark1"/>
                        <el-text style="font-weight: bold;margin-left: 5px;margin-right: 5px"><=得分<</el-text>
                        <el-input-number v-model="rightBoundary2" :min="1" :max="100" class="input5" disabled/>
                        <el-text class="content1">评价:</el-text>
                        <el-input v-model="scoreLevel2" placeholder="" class="input4"/>
                    </el-form-item>
                    <el-form-item   label="">
                        <el-input-number v-model="leftBoundary3"  :min="0" :max="100" class="input5" @change="changeMark2"/>
                        <el-text style="font-weight: bold;margin-left: 5px;margin-right: 5px"><=得分<</el-text>
                        <el-input-number v-model="rightBoundary3" :min="1" :max="100" class="input5" disabled/>
                        <el-text class="content1">评价:</el-text>
                        <el-input v-model="scoreLevel3" placeholder="" class="input4"/>
                    </el-form-item>
                    <el-form-item style="margin-top: 30px;margin-left: 30px"  label="结束页面" prop="finishExamState">
                        <el-radio-group v-model="form.finishExamState">
                            <el-radio :label="0">不显示成绩</el-radio>
                            <el-radio :label="1">显示成绩、排名、答案详情、答案解析</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        </div>
        <el-dialog v-model="innerVisible" width="350" style="font-weight: bold;color: red" title="提醒!!!" append-to-body center>
            <span style="font-size: 16px;margin-left: 30px;color: red">考试区间需大于考试时长,请重新设定</span>
        </el-dialog>
        <!-- 编辑、新增  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)" @parentsEmit="pEmitData"/>
        <!-- 自选  编辑、新增  -->
        <form-select-dialog ref="formSelectDialogRef" @refresh="getDataList(false)" @parentsEmit="pEmitData"/>
    </div>
</template>

<script setup lang="ts" name="KsglExamListIndex1">
    import { useDict } from '/@/hooks/dict';
    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj,getUsers,score,getListForH5ById,getZsglCertificateList} from '/@/api/train/ksglExamList'
    import { rule } from '/@/utils/validate';
    import {ref} from "vue";
    import {deptTree, syspost} from "/@/api/train/kszlData";
    import {ElMessage} from "element-plus";
    import {useRouter} from "vue-router";
    const emit = defineEmits(['refresh']);
    import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes'
    const persons = ref([])
    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const FormSelectDialog = defineAsyncComponent(() => import('./formselect.vue'));
    const cascaderAddr1 = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
    // 定义变量内容
    const router = useRouter();
    const storesTagsViewRoutes = useTagsViewRoutes();
    const dataFormRef = ref();
    const started = ref(false);
    const started1 = ref(false);
    const visible = ref(false)
    const loading = ref(false)
    const checked = ref(false)
    const innerVisible = ref(false)
    const isShow = ref(true)
    const dataList = ref<any[]>([]);
    // 定义变量内容1
    const formDialogRef = ref()
    const formSelectDialogRef = ref()
    const groupId = ref()
    const durationInMinutes = ref()
    //参与组织数据
    const options1 = ref<any[]>([]);
    //部门主键
    const pkDept = ref()
    const currentTime  = ref()
    const leftBoundary0 = ref()
    const leftBoundary1 = ref()
    const leftBoundary2 = ref()
    const leftBoundary3 = ref()
    const rightBoundary0 = ref()
    const rightBoundary1 = ref()
    const rightBoundary2 = ref()
    const rightBoundary3 = ref()
    const scoreLevel0 = ref()
    const scoreLevel1 = ref()
    const scoreLevel2 = ref()
    const scoreLevel3 = ref()
    //分数集合
    const scoreList = reactive([])
    const certificateList = reactive([])
    //学习岗位
    const postList =reactive([])
    // 提交表单数据
    const form = reactive({
        levelEntityList:[],
        passingScore:"60",
        certificateId:'',
        id:'',
        examName: '',
        examLabel: '',
        adminName: '',
        examPaperName: '',
        examType: 0,
        examRemark: '',
        groupIds:[],
        transcriptEntityList:[],
        postNames:[],
        postIds:[],
        persons:[{}],
        submitOntimeState: 0,
        submitInadvanceState: 0,
        allowStartTime: '15',
        wrongQuestionFirstState: 1,
        electronicInvigilationState: 0,
        grantCertificateState:1,
        allowMakeupExamState: 0,
        faceRecognitionTimes: '10',
        certificateHolderState:1,
        cutscreenTimes: '3',
        makeupTimes:'1',
        sendRemindTime: '10',
        examTimeState:null,
        examTime: '60',
        specifyTimeStart: '',
        specifyTimeEnd: '',
        questionOrder: 1,
        optionsOrder: 1,
        finishExamState: 1,
    });
    const route = useRoute();
    const timer1 = ref<number | null>(null);
    const processedPKPosts = ref([])
    const groupNames = ref([])
    const groupIds = ref([])
    const flag = ref()
    const personList = reactive([])
    // 定义校验规则
    const dataRules = ref({
        examName: [{required: true, message: '考试名称不能为空', trigger: 'blur'}],
        specifyTimeStart: [{required: false, message: '开始时间不能为空', trigger: 'blur'}],
        specifyTimeEnd: [{required: false, message: '结束时间不能为空', trigger: 'blur'}],
        examPaperName: [{required: true, message: '试卷名称不能为空', trigger: 'blur'}],
        examLabel: [{required: true, message: '考试标签不能为空', trigger: 'blur'}],
        adminName: [{required: true, message: '管理员姓名不能为空', trigger: 'blur'}],
        adminUserName: [{required: true, message: '管理员工号不能为空', trigger: 'blur'}],
        persons: [{required: true, message: '参与人员不能为空', trigger: 'blur'}],
        groupIds: [{required: true, message: '考试组织名称不能为空', trigger: 'blur'}],
        postNames: [{required: true, message: '参考岗位名称不能为空', trigger: 'blur'}],
        examType: [{required: true, message: '考试类型不能为空', trigger: 'blur'}],
        submitOntimeState: [{required: true, message: '定时交卷不能为空', trigger: 'blur'}],
        submitInadvanceState: [{required: true, message: '提前交卷不能为空', trigger: 'blur'}],
        faceRecognitionTimes: [{required: true, message: '人脸识别次数不能为空', trigger: 'blur'}],
        electronicInvigilationState: [{required: true, message: '电子监考不能为空', trigger: 'blur'}],
        allowMakeupExamState: [{required: true, message: '是否允许补考不能为空', trigger: 'blur'}],
        makeupTimes: [{required: true, message: '是否允许补考次数不能为空', trigger: 'blur'}],
        allowStartTime: [{required: true, message: '考试开始后的时间不能为空', trigger: 'blur'}],
        cutscreenTimes: [{required: true, message: '允许切屏次数不能为空', trigger: 'blur'}],
        examTime: [{required: true, message: '考试时长不能为空', trigger: 'blur'}],
        sendRemindTime: [{required: true, message: '考试结束前不能为空', trigger: 'blur'}],
        questionOrder: [{required: true, message: '试题顺序不能为空', trigger: 'blur'}],
        optionsOrder: [{required: true, message: '选项顺序不能为空', trigger: 'blur'}],
        examTimeState: [{required: true, message: '考试状态不能为空', trigger: 'blur'}],
        finishExamState: [{required: true, message: '结束页面不能为空', trigger: 'blur'}],
    })
    //挂载完毕
    onMounted(()=>{
        flag.value = route.query.flag
        if (route.query.flag == 0){
            let arr = [
                {id: 1, leftBoundary: 0, rightBoundary: 60, scoreLevel: "不及格",},
                {id: 2, leftBoundary: 60, rightBoundary: 80, scoreLevel: "及格",},
                {id: 3, leftBoundary: 80, rightBoundary: 100, scoreLevel: "优秀",},
                {id: 4, leftBoundary: 100, rightBoundary: 100, scoreLevel: "完美",}
            ]
            Object.assign(scoreList,arr)
            leftBoundary0.value = scoreList[0].leftBoundary
            leftBoundary1.value = scoreList[1].leftBoundary
            leftBoundary2.value = scoreList[2].leftBoundary
            leftBoundary3.value = scoreList[3].leftBoundary
            rightBoundary0.value = scoreList[0].rightBoundary
            rightBoundary1.value = scoreList[1].rightBoundary
            rightBoundary2.value = scoreList[2].rightBoundary
            rightBoundary3.value = scoreList[3].rightBoundary
            scoreLevel0.value = scoreList[0].scoreLevel
            scoreLevel1.value = scoreList[1].scoreLevel
            scoreLevel2.value = scoreList[2].scoreLevel
            scoreLevel3.value = scoreList[3].scoreLevel
            form.passingScore =  leftBoundary1.value
        }else {
            form.examId  = route.query.examId
            getListForH5ById(form.examId).then((res=>{
                persons.value.length = 0
                form.transcriptEntityList.length = 0
                Object.assign(form,res.data)
                if(form.examType==0 && form.examTimeState==1){
                    // console.log('正式考試指定時間')
                    timer1.value = setInterval(checkExamTime, 1000)
                }
                form.groupIds =  form.groupId.split(",")
                form.groupNames =  form.groupName.split("/")
                form.postNames =  form.postName.split(",")
                form.postIds =  form.postId.split(",")
                getPostList()
                getPerson()
                form.transcriptEntityList.forEach(item =>{
                   let username = item.userName
                    persons.value.push(username)
                })
                score(form.examId).then((res=>{
                    Object.assign(scoreList,res.data)
                    leftBoundary0.value = scoreList[0].leftBoundary
                    leftBoundary1.value = scoreList[1].leftBoundary
                    leftBoundary2.value = scoreList[2].leftBoundary
                    leftBoundary3.value = scoreList[3].leftBoundary
                    rightBoundary0.value = scoreList[0].rightBoundary
                    rightBoundary1.value = scoreList[1].rightBoundary
                    rightBoundary2.value = scoreList[2].rightBoundary
                    rightBoundary3.value = scoreList[3].rightBoundary
                    scoreLevel0.value = scoreList[0].scoreLevel
                    scoreLevel1.value = scoreList[1].scoreLevel
                    scoreLevel2.value = scoreList[2].scoreLevel
                    scoreLevel3.value = scoreList[3].scoreLevel
                    form.passingScore =  leftBoundary1.value
                }))
            }))
        }
        deptTreeList()
        getCertificate()
    })
    const changeScore = (val:any)=>{
        leftBoundary1.value =  form.passingScore
        scoreList[1].leftBoundary = leftBoundary1.value
        rightBoundary0.value =  leftBoundary1.value
        scoreList[0].rightBoundary =  leftBoundary1.value
    }
    const change1 = (val:any)=>{
        if(val==1){
            form.grantCertificateState = 1
        }
    }
    const change2 = (val:any)=>{
        // console.log('val',val)
        if(val==0){
            form.certificateId=''
        }
    }
    const change3 = (val:any)=>{
        console.log('val',val)
        if(val==0){
            checked.value=true
            selectAll()
        }
    }
    //获取证书
    const getCertificate = ()=>{
        getZsglCertificateList().then(res=>{
            Object.assign(certificateList,res)
        })
    }
    const checkExamTime = ()=>{
        //当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // console.log('当前时间',now,currentTime.value)
        if (currentTime.value >= form.specifyTimeStart) {
             started.value = true
            clearInterval(timer1.value);// 停止定时器，因为考试已经开始了
        }
    }
    const changeMark =(val:any)=>{
        scoreList[1].leftBoundary = val
        form.passingScore =  val
        scoreList[0].rightBoundary = val
        rightBoundary0.value = val
    }
    const changeMark1 =(val:any)=>{
        scoreList[2].leftBoundary = val
        scoreList[1].rightBoundary = val
        rightBoundary1.value = val
    }
    const changeMark2 =(val:any)=>{
        scoreList[3].leftBoundary = val
        scoreList[2].rightBoundary = val
        rightBoundary2.value = val
    }
    //人员全选
    const selectAll=() =>{
        console.log('persons.value.length',persons.value.length,'personList.length',personList.length)
        if (checked.value) {
            persons.value = personList.map(person => person.username);
        }else {
            persons.value.length = 0
            form.persons.length = 0
        }
    }
    const changeTime = (val:any) =>{
        if(form.examType==0){
            const startTime = form.specifyTimeStart;
            const duration = form.examTime;
            form.specifyTimeEnd = calculateEndTime(startTime, duration);
        }
    }
//计算结束时间
    const calculateEndTime =(startTimeStr:string, durationInMinutes:string)=> {
        const startTime = new Date(startTimeStr);
        // 检查开始时间是否有效
        if (isNaN(startTime.getTime())) {
            throw new Error('Invalid start time');
        }
        // 计算结束时间（将时长转换为毫秒并添加到开始时间的毫秒数上）
        const endTime = new Date(startTime.getTime() + durationInMinutes * 60000);
        const offset = endTime.getTimezoneOffset() * 60000; // 获取时区偏移量（以毫秒为单位）
        const utcEndTime = new Date(endTime.getTime() - offset); // 转换为 UTC 时间
        const endTimeStr = utcEndTime.toISOString().slice(0, 19).replace('T', ' '); // 格式化 UTC 时间字符串
        // 返回结束时间字符串
        return endTimeStr;
    }
    const pEmitData=(data:any)=>{
        if(data.id!==undefined){
            form.examPaperId = data.id
            form.examPaperName = data.name
            flag.value = 1
            isShow.value = true
        }else {
            form.examPaperName = data.name
        }
        // console.log('data----',data,form.examPaperId)
    }
//计算两个时间之间的差值
    const calculateDuration =()=> {
        // 将开始时间和结束时间字符串转换为Date对象
        const startDate = new Date(form.specifyTimeStart);
        const endDate = new Date(form.specifyTimeEnd);
        // 计算两个时间之间的差值（毫秒）
        const diffInMs = endDate.getTime() - startDate.getTime();
        // 将毫秒转换为分钟
        durationInMinutes.value = Math.round(diffInMs / (1000 * 60));
    }
//参考组织改变事件
    const handleCascaderChange1 = (item: any) => {
      if(item!==null){
          groupId.value = item[item.length-1]
          groupIds.value = item
          if (cascaderAddr1.value) {
              // 获取选中节点的 pathLabels
              groupNames.value = cascaderAddr1.value.getCheckedNodes()[0].pathLabels
          }
          form.groupIds = groupIds.value
          form.groupNames = groupNames.value
          form.postNames = []
          postList.length = 0
          persons.value = []
          // console.log('Path Labels:', form.groupIds,form.groupNames);
          isShow.value = false
          flag.value = 0
          form.examPaperName = ''
      }else {
          form.postNames = []
          postList.length = 0
          persons.value = []
      }
    };
    //参考组织下拉框关闭事件
    const handleVisibleChange = (isVisible:any) => {
        if (!isVisible) {
            if (cascaderAddr1.value) {
                const checkedNodes = cascaderAddr1.value.getCheckedNodes(); // 输出选中的节点信息
                groupId.value = checkedNodes[0].value
                // console.log('groupId.value',groupId.value,checkedNodes);
            }
            getPostList()
        }
    };
    const getItem1=(val:any) =>{
       if(val.length !==0){
           form.postIds.length = 0
           personList.length = 0
           persons.value.length = 0
           postList.forEach(item => {
               for (let i = 0; i < val.length; i++) {
                   if (item.postName == val[i]) {
                       form.postIds.push(item.postsString)
                   }
               }
           })
           isShow.value = false
           flag.value = 0
           form.examPaperName = ''
           getAllPerson()
       }else {
           form.postIds.length = 0
           personList.length = 0
           persons.value.length = 0
       }
    }
//人员全选
    const getAllPerson = ()=>{
        processedPKPosts.value.length=0
        form.postIds.forEach(item=>{
            if (item.includes(',')) {
                // 如果项包含逗号，则按逗号拆分
                const splitItems = item.split(',');
                splitItems.forEach(splitItem=>{
                    processedPKPosts.value.push(splitItem.trim())
                })
            }else {
                processedPKPosts.value.push(item)
            }
        })
        // 使用map将数组中的每个元素转换为URL参数形式，并用join连接它们
        const params = processedPKPosts.value.map((id, index) => {
            // 注意：这里index > 0时添加'&'，因为第一个元素前不需要
            return index > 0 ? '&pkPosts=' + id : 'pkPosts=' + id;
        }).join('');
        getUsers(params).then((res=>{
            Object.assign(personList,res)
            checked.value = true
            selectAll()
        }))
    }
//人员下拉框
    const getPerson = ()=>{
        processedPKPosts.value.length=0
        form.postIds.forEach(item=>{
            if (item.includes(',')) {
                const splitItems = item.split(',');
                splitItems.forEach(splitItem=>{
                    processedPKPosts.value.push(splitItem.trim())
                })
            }else {
                processedPKPosts.value.push(item)
            }
        })
        const params = processedPKPosts.value.map((id, index) => {
            return index > 0 ? '&pkPosts=' + id : 'pkPosts=' + id;
        }).join('');
        getUsers(params).then((res=>{
            Object.assign(personList,res)
            if(form.transcriptEntityList.length<personList.length)
            {
                checked.value = false
            }else {
                checked.value = true
            }
        }))
    }
    const getItem2=(val:any) =>{
        if(persons.value.length<personList.length){
            checked.value = false
        }else if(persons.value.length == personList.length){
            checked.value = true
        }
    }
    const getItem3=(val:any)=>{
        form.certificateStartTime = ''
        form.certificateEndTime = ''
        certificateList.forEach(item => {
                if (item.certificateTemplateId == val) {
                      form.certificateName = item.certificateTemplateName
                     if(item.startTime && item.endTime){
                         form.certificateStartTime = item.startTime
                         form.certificateEndTime = item.endTime
                     }
                }
        })
        console.log('form',form)
    }
// 参与组织
    const deptTreeList = async () => {
        deptTree().then((res) => {
            options1.value = res.data;
        });
    };
//学习岗位
    const getPostList =  () =>{
        postList.length = 0;
        if(route.query.flag==1){
            const num = form.groupIds
            syspost(num[num.length-1]).then((res: any) => {
                Object.assign(postList, res.data)
            });
        }else {
            const num = groupId.value
            syspost(num).then((res: any) => {
                postList.length = 0;
                Object.assign(postList, res.data)
                // console.log('postList',postList)
            });
        }
    }
//保存
    const onSubmit = () =>{
        started1.value = true
        form.persons.length = 0
        personList.forEach(item =>{
            for (let i = 0; i < persons.value.length; i++) {
                if (item.username == persons.value[i]) {
                    form.persons.push({
                        personName:item.name,
                        postId:item.pkPost,
                        userName:item.username,
                        postName:item.postName,
                        pkPsndoc:item.pkPsndoc,
                        groupId:form.groupIds,
                        groupName:form.groupNames,
                    })
                }
            }
        })
        form.levelEntityList.length = 0
        scoreList.forEach(item=>{
            let obj ={
                leftBoundary:item.leftBoundary,
                rightBoundary:item.rightBoundary,
                scoreLevel:item.scoreLevel,
            }
            form.levelEntityList.push(obj)
        })
        if(form.examTimeState==1){
            dataRules.value.specifyTimeStart[0].required = true
            dataRules.value.specifyTimeEnd[0].required = true
        }
        dataFormRef.value?.validate((valid:any) => {
            if (valid) {
                if(form.examTimeState==1 && form.examType==1){   //指定时间且模拟考试
                    calculateDuration()
                        if(form.specifyTimeStart>=form.specifyTimeEnd){
                            alert('结束时间应该晚于开始时间,请修改');
                        }else if(durationInMinutes.value<Number(form.examTime)){
                            alert('设置考试时间间隔应该大于考试时长'+form.examTime+',请修改');
                        }else {
                            if(form.examId==undefined){
                                // console.log('form',form)
                                addObj(form).then((res=>{
                                    ElMessage({
                                        message: '创建成功',
                                        type: 'success',
                                    })
                                    const path = '/train/ksglExamList/index';
                                    // storesTagsViewRoutes.delFavoriteRoutes(router.currentRoute.value.path);
                                    router.push({path})
                                })).catch(error=>{
                                    started1.value = false
                                    alert('失败');
                                })
                            }else {
                                delete form.groupId;
                                delete form.postName;
                                delete form.postId;
                                delete form.transcriptEntityList;
                                putObj(form).then((res=>{
                                    ElMessage({
                                        message: '修改成功',
                                        type: 'success',
                                    })
                                    const path = '/train/ksglExamList/index';
                                    // storesTagsViewRoutes.delFavoriteRoutes(router.currentRoute.value.path);
                                    router.push({path})
                                })).catch(error=>{
                                    started1.value = false
                                    alert(error.msg);
                                })
                            }
                        }
                }else {
                    if(form.examId==undefined){
                        addObj(form).then((res=>{
                            ElMessage({
                                message: '创建成功',
                                type: 'success',
                            })
                            const path = '/train/ksglExamList/index';
                            console.log('router.currentRoute.value.path',router.currentRoute.value.path)
                            storesTagsViewRoutes.delFavoriteRoutes(router.currentRoute.value.path);
                            router.push({path})
                        })).catch(error=>{
                            started1.value = false
                            alert('失败');
                        })
                    }else {
                        delete form.groupId;
                        delete form.postName;
                        delete form.postId;
                        delete form.transcriptEntityList;
                        putObj(form).then((res=>{
                            ElMessage({
                                message: '修改成功',
                                type: 'success',
                            })
                            const path = '/train/ksglExamList/index';
                            console.log('router.currentRoute.value.path',router)
                            storesTagsViewRoutes.delFavoriteRoutes(router.currentRoute.value.path);
                            router.push({path})
                        })).catch(error=>{
                            started1.value = false
                            alert(error.msg);
                        })
                    }
                }
            }else {
                started1.value = false
            }
        })
    }
    // 确保组件卸载时清除定时器
    onUnmounted(() => {
        clearInterval(timer1.value);
    });
</script>
<style lang="scss" scoped>
    .custom-header {
        .el-checkbox {
            display: flex;
            height: unset;
        }
    }
    .scroll{
        overflow-y:scroll;
        overflow-x:hidden;
        height:100%
    }
    .input1{
        width: 40px;
        margin-right: 5px
    }
    .input2{
        width: 40px;
        margin-left: 5px
    }
    .input3{
        height: 32px;
        line-height: 32px;
    }
    .input4{
        border: none; /* 移除 input 的边框，如果需要的话 */
        text-align: center; /* 这将确保文本在 input 中居中 */
        width: 70px;
        margin-right: 10px
    }
    .input5{
        width: 110px;
    }
    .line{
        border-top: 1px dashed #817B7B;
        width: 1350px;
        height: 0;
        margin-left: 40px
    }
    .content{
        line-height: 50px;
        margin-left: 10px;
        font-size: 16px
    }
    .content1{
        margin-left: 14px;
        font-weight: bold
    }
    .el-row{
        margin-top: 5px;
    }
</style>
